package cn.damai.mine.thread.countDownLatch.healthchecker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ApplicationStartupUtil {

	private static List<BaseHealthChecker> _services;
	private static CountDownLatch _laLatch;
	
	public static Boolean checkExternalService(){
		
		_laLatch = new CountDownLatch(3);
		
		_services = new ArrayList<BaseHealthChecker>();
		_services.add(new NetworkHealthChecker(_laLatch));
		_services.add(new DatabaseHealthChecker(_laLatch));
		_services.add(new CacheHealthChecker(_laLatch));
		
		//配置文件初始化线程池的方法：
		/*
		appDefault.properties  增加	executor.init.count=10	配置
		
		applicationContext.xml 文件增加类ExecutorUtil的实例   注意写在加载appDefault.properties的后面
		<bean id="executorUtil" class="cn.damai.wireless.statics.handler.ExecutorUtil">
			<constructor-arg value="${executor.init.count}" />
		</bean>
		
		注入：
		在需要使用的地方使用下面方法注入
		@Resource
		ExecutorUtil executorUtil;
		
		使用：
		executorUtil.getExecutorService().execute(executorUtil.getExecutorService().execute(checker););
		
		*/
		
		Executor executor  = Executors.newFixedThreadPool(_services.size());
		
		for (BaseHealthChecker checker : _services) {
			executor.execute(checker);
		}
		
		try {
			_laLatch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		for (BaseHealthChecker checker : _services) {
			System.out.println(checker.get_resultStr());
		}
		
		for (BaseHealthChecker checker : _services) {
			if (!checker.is_serviceUp()) {
				return false;
			}
		}
		return true;
	}
	
	public static void main(String[] args) {
		
		boolean result = checkExternalService();
		System.out.println("External services validation completed !! Result was :: "+ result);
		
	}
	
}
